package com.wms.service.impl;

import com.wms.entity.Warehouse;
import com.wms.mapper.WarehouseMapper;
import com.wms.service.WarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class WarehouseServiceImpl implements WarehouseService {

    @Autowired
    private WarehouseMapper warehouseMapper;

    @Override
    public List<Warehouse> getAllWarehouses() {
        return warehouseMapper.selectAll();
    }

    @Override
    @Transactional
    public void addEntry(Integer companyId, Integer totalItems) {
        Warehouse warehouse = warehouseMapper.findByCompanyId(companyId);
        if (warehouse == null) {
            warehouse = new Warehouse();
            warehouse.setCompanyId(companyId);
            warehouse.setTotalItems(totalItems);
            warehouseMapper.insert(warehouse);
        } else {
            warehouse.setTotalItems(warehouse.getTotalItems() + totalItems);
            warehouseMapper.update(warehouse);
        }
    }

    @Override
    @Transactional
    public void addExit(Integer companyId, Integer totalItems) {
        Warehouse warehouse = warehouseMapper.findByCompanyId(companyId);
        if (warehouse != null) {
            warehouse.setTotalItems(warehouse.getTotalItems() - totalItems);
            warehouseMapper.update(warehouse);
        }
    }
}
